package own.stu.inter.loadbalance.httpclient;

import io.netty.buffer.PooledByteBufAllocator;
import io.netty.channel.EventLoopGroup;
import org.asynchttpclient.AsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClient;
import org.asynchttpclient.DefaultAsyncHttpClientConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

public class HttpClient {

    protected static Logger logger = LoggerFactory.getLogger(HttpClient.class);

    private AsyncHttpClient asyncHttpClient;

    private DefaultAsyncHttpClientConfig.Builder clientBuilder;

    private HttpClientConfig clientConfig;

    private EventLoopGroup eventLoopGroupWork;

    public HttpClient(EventLoopGroup eventLoopGroupWork) {
        this(new HttpClientConfig(), eventLoopGroupWork);
    }

    public HttpClient(HttpClientConfig clientConfig, EventLoopGroup eventLoopGroupWork) {
        this.clientConfig = clientConfig;
        this.eventLoopGroupWork = eventLoopGroupWork;
        //	在构造函数调用初始化方法
        init();
    }

    /**
     * 初始化AsyncHttpClient
     */
    public void init() {
        this.clientBuilder = new DefaultAsyncHttpClientConfig.Builder()
                .setFollowRedirect(false)
                .setEventLoopGroup(eventLoopGroupWork)
                .setConnectTimeout(clientConfig.getHttpConnectTimeout())
                .setRequestTimeout(clientConfig.getHttpRequestTimeout())
                .setMaxRequestRetry(clientConfig.getHttpMaxRequestRetry())
                .setAllocator(PooledByteBufAllocator.DEFAULT)
                .setCompressionEnforced(true)
                .setMaxConnections(clientConfig.getHttpMaxConnections())
                .setMaxConnectionsPerHost(clientConfig.getHttpConnectionsPerHost())
                .setPooledConnectionIdleTimeout(clientConfig.getHttpPooledConnectionIdleTimeout());
    }

    public void start() {
        this.asyncHttpClient = new DefaultAsyncHttpClient(clientBuilder.build());
        AsyncHttpHelper.getInstance().initialized(asyncHttpClient);
    }

    public void shutdown() {
        if (asyncHttpClient != null) {
            try {
                this.asyncHttpClient.close();
            } catch (IOException e) {
                // ignore
                logger.error("httpclient shutdown error", e);
            }
        }
    }
}